var rootPath = getRootPath();

$(function() {

	jQuery.validator.addMethod("checkGname", function(value, element) {
		var oriGname = $("#oriGname").val();
		return checkGname(value,oriGname);
	}, "等级名称已存在");
	
	$("#gradeEditForm").validate({
		rules : {
			gname :  {
				required : true,
				checkGname : true
			}
		},
		onkeyup:false,
		focusCleanup:true,
		success:"valid",
		submitHandler:function(form){
			var gid = $("#gid").val();
			var gname = $("#gname").val();
			var pid = $("option:selected").val();
			$.ajax({
				url: rootPath + '/grade/' + gid,
		        type: 'PUT',
		        data: JSON.stringify({
		        	"gid" : gid,
		        	"gname" : gname,
	            	"pid" : pid
		        }),
	            contentType: 'application/json;charset=UTF-8', 
		        success: function (data) {
					if(data.returnCode == "0000") {						
						layer.msg('成功更新等级!',{icon:1,time:1000},function() {						
							parent.window.location.href = rootPath + '/gradePage';
							var index = parent.layer.getFrameIndex(window.name);
							parent.layer.close(index);
						});
					} else {
						layer.alert(data.returnMessage);
					}
		        },
		        error: function (jqXHR, textStatus, errorThrown) {
		        	layer.alert("更新等级失败:(");
		        }
		    });
		}
	});
});

function checkGname(gname,oriGname) {
	var isValidGname = true;
	if(gname != oriGname) {
		$.ajax({
			url: rootPath + '/grade/checkGname',
	        type: 'GET',
	        async: false,
	        data: {
	        	"gname" : gname
	        },
	        success: function (data) {
	        	if(data != "true") {
	        		isValidGname = false;
	        	}
	        },
	        error: function (jqXHR, textStatus, errorThrown) {
	        	layer.alert("error:(");
	        }
	    });
	}
	return isValidGname;
}